package com.yuanfeng.job.config;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuanfeng.job.entity.JobPlatformEntity;
import com.yuanfeng.job.job.BaseJob;
import com.yuanfeng.job.service.JobPlatformService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ScheduledStarted implements CommandLineRunner {

	private static final Logger logger = LoggerFactory.getLogger(ScheduledStarted.class);

	// 加入Qulifier注解，通过名称注入bean
	@Autowired
	@Qualifier("Scheduler")
	private Scheduler scheduler;

	@Autowired
	private JobPlatformService jobPlatformService;

	@Override
	public void run(String... args) throws Exception {
		logger.info("start last left scheduled");

        //从表中取定时任务名称和时间
		List<JobPlatformEntity> jobs = jobPlatformService.list(new LambdaQueryWrapper<JobPlatformEntity>()
							.eq(JobPlatformEntity::getStatus,0));
		if(jobs.size() ==0){
			return;
		}
		for(JobPlatformEntity job : jobs){
			String invokeTarget = job.getInvokeTarget();
			String cronExpression = job.getCronExpression();
			addJob(invokeTarget,"2",cronExpression);
			logger.info("定时任务" + invokeTarget + "开始执行" + cronExpression );
 		}

		//从Redis中取定时任务调度时间
//		Set<String> schedulerdSet = RedisUtil.smembers("scheduler");
//		if (0 ==  schedulerdSet.size()) {
//			return;
//		}
//		for(String scheculer:schedulerdSet){
//			String trigger = RedisUtil.get(scheculer);
//			addJob(scheculer,"2",trigger);
//			logger.info("定时任务" + scheculer + "开始执行" + trigger );
//		}


	}

	public void addJob(String jobClassName, String jobGroupName, String cronExpression) throws Exception {

		// 启动调度器
		scheduler.start();

		// 构建job信息
		JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass())
				.withIdentity(jobClassName, jobGroupName).build();

		// 表达式调度构建器(即任务执行的时间)     cronExpression

		CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

		// 按新的cronExpression表达式构建一个新的trigger
		CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobClassName, jobGroupName)
				.withSchedule(scheduleBuilder).build();

		try {
			scheduler.scheduleJob(jobDetail, trigger);

		} catch (SchedulerException e) {
			System.out.println("创建定时任务失败" + e);
			throw new Exception("创建定时任务失败");
		}
	}
	
	public BaseJob getClass(String classname) throws Exception
	{
		Class<?> class1 = Class.forName(classname);
		return (BaseJob)class1.newInstance();
	}

}
